package com.lifp.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author lifp
 * @date 2023/04/24
 */
@Slf4j
public class FileUtil {

    /**
     * 通过url 获取InputStream
     * @param strUrl url
     * @return java.io.InputStream
     * @author lifp
     * @date 2023/4/24
     **/
    public static InputStream getInputStreamByUrl(String strUrl) {
        HttpURLConnection conn = null;
        try {
            URL url = new URL(strUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(20 * 1000);
            final ByteArrayOutputStream output = new ByteArrayOutputStream();
            IOUtils.copy(conn.getInputStream(), output);
            return new ByteArrayInputStream(output.toByteArray());
        } catch (Exception e) {
            log.error("url get inputStream Exception => url:[{}]", strUrl, e);
            return null;
        } finally {
            try {
                if (conn != null) {
                    conn.disconnect();
                }
            } catch (Exception e) {
                log.error("url get inputStream conn close Exception => url:[{}]", strUrl, e);
            }
        }
    }

    /**
     * 通过url获取文件
     * @param url
     * @return java.io.File
     * @author lifp
     * @date 2023/4/24
     **/
    public static File getFileFromUrl(String url) throws Exception {
        //对本地文件命名
        String fileName = url.substring(url.lastIndexOf("."),
                url.lastIndexOf("?")>0?url.lastIndexOf("?"):url.length());

        log.info("file name:" + fileName);
        File file = null;
        URL urlfile;
        InputStream inStream = null;
        OutputStream os = null;
        try {
            file = File.createTempFile("net_url", fileName);
            //下载
            urlfile = new URL(url);
            inStream = urlfile.openStream();
            os = new FileOutputStream(file);

            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = inStream.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            log.error("FileUtils getFileFromUrl =>", e);
            return null;
        } finally {
            try {
                if (null != os) {
                    os.close();
                }
                if (null != inStream) {
                    inStream.close();
                }
            } catch (Exception e) {
                log.error("FileUtils getFileFromUrl =>", e);
            }
        }
        return file;
    }
}
